﻿import ajaxOptions = require("AjaxCallsOptions");

export function callService(options: ajaxOptions.AjaxOptions, instance: kendo.data.ObservableObject, callback: (instance: kendo.data.ObservableObject, result:ajaxOptions.AjaxOptionsCallbackInput)=>void) {
        $.ajax({
            url: options.url,
            type: options.requestType,
            data: options.data,
            dataType: options.dataType,

            // Add HTTP headers if configured
            beforeSend: (xhr) => {
                if (options.httpHeader !== undefined && options.headerValue !== undefined) {
                    xhr.setRequestHeader(options.httpHeader, options.headerValue);
                }
            },

            // on successfull ajax call back
            success: (resutlData, status, xhr) => {
                var result = new ajaxOptions.AjaxOptionsCallbackInput();
                result.data = resutlData;
                result.success = true;
                callback(instance, result);
            },

            //Callback function in case of an error
            error: (xhr, status, errorThrown) => {
                switch (xhr.status) {
                    case 401:
                        {
                            alert('401 Unauthorized access detected. Please check the credentials you enter. ' + errorThrown);
                            break;
                        }

                    case 500:
                        {
                            alert('500 Internal server error. ' + errorThrown);
                            break;
                        }

                    default:
                        {
                            alert('Unexpected error. ' + errorThrown);
                            break;
                        }
                }

                var result = new ajaxOptions.AjaxOptionsCallbackInput();
                result.success = false;
                callback(instance, result);
            }
        });
    }
